package app.server.project.main.service.db.entity.user;

import app.server.project.core.syndb.SynDBMgr;
import app.server.project.core.syndb.SynSpeed;
import app.server.project.core.util.MathUtil;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.Id;
import jakarta.persistence.Transient;
import lombok.Data;
import org.hibernate.annotations.Comment;

import java.time.LocalDateTime;

@Data
@Entity(name = "user_usdt")
@TableName("user_usdt")
@Comment(value = "用户u币信息表")
@SynSpeed
public class UserUSDTEntity {

    @Id
    @Column(name = "id")
    @Comment("用户主键")
    @TableId("id")
    private long id;


    @Column(name = "usd_val")
    @Comment("usdt值")
    @TableField("usd_val")
    private long usdVal;


    @TableField("create_time")
    @Comment("创建时间")
    @Column(name = "create_time")
    private LocalDateTime createTime;

    @Transient
    @TableField(exist = false)
    private boolean synDb = false;

    public static UserUSDTEntity of(long userId) {
        var ret = new UserUSDTEntity();
        ret.setId(userId);
        ret.setSynDb(true);
        ret.setCreateTime(LocalDateTime.now());
        return ret;
    }


    public void setCreateTime(LocalDateTime createTime) {
        this.createTime = createTime;
        if (!this.synDb) return;
        SynDBMgr.addChangeData(UserUSDTEntity::getCreateTime, this);
    }


    public void setUsdVal(long usdVal) {
        this.usdVal = usdVal;
        if (!this.synDb) return;
        SynDBMgr.addChangeData(UserUSDTEntity::getUsdVal, this);
    }


    public void addUsdVal(long val) {
        var ret = MathUtil.canAddNum(this.usdVal, val);
        this.usdVal += ret;
        if (!this.synDb) return;
        SynDBMgr.addChangeData(UserUSDTEntity::getUsdVal, this);
    }

    public boolean consume(long val) {
        if (val > this.usdVal) return false;
        this.usdVal -= val;
        this.setUsdVal(this.usdVal);
        return true;
    }

}
